//
// TileFactory.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Reflection;
using System.Collections.Generic;

using Gtk;

using Dashboard;
using Dashboard.Util;
using Dashboard.Mint.Theatrics;

namespace Dashboard.Mint.Tiles {

	public static class TileFactory {

		private static Dictionary<string, Type> tiles = new Dictionary <string, Type> ();

		static TileFactory () 
		{
			List<Type> tile_types = ReflectionFu.ScanAssemblyForClass (Assembly.GetExecutingAssembly (), typeof (Tile));
			
			foreach (Type tile_type in tile_types) { 
				object[] attributes = Attribute.GetCustomAttributes (tile_type, typeof (TileAttribute));
				
				foreach (object attribute in attributes) {
					TileAttribute tile_attribute = attribute as TileAttribute;
					
					if (tile_attribute == null)
						continue;
					
					tiles.Add (tile_attribute.Type, tile_type);
				}
			}
		}

		public static Tile BuildTile (Match match)
		{
			if (!tiles.ContainsKey (match.Type))
				return null;

			try {
				return System.Activator.CreateInstance (tiles [match.Type], new object[] {match}) as Tile;
			} catch (Exception e) {
				Console.WriteLine ("Caught exception while instantiating tile: {0}", match.Type);
				Console.WriteLine (e);
				return null;
			}
		}
	}
}
